<?php

namespace App\Module\Admin\Service;

use App\Constants\Constant;
use App\Model\Activity;
use App\Model\Resource;
use App\Module\Admin\Request\Activity\CreateRequest;
use App\Module\Admin\Request\Activity\UpdateRequest;
use Hyperf\DbConnection\Db;

class ActivityService {

    public function search($pagesize){
        return Activity::query()->latest("act_id")->with(["resources",'users','payments'])->paginate($pagesize);
    }

    public function create(CreateRequest $request){
        return Db::transaction(function() use($request){
            $model = new Activity();
            $model->fill($request->all());
            $model->save();

            $resources = $request->input("resources");
            foreach ($resources as $v){
                $resource = new Resource();
                $resource->setAttribute("source_id",$model->act_id);
                $resource->setAttribute("uri",$v);
                $resource->setAttribute("origin",Constant::ORIGIN_ACTIVITY);
                $resource->save();
            }
        });
    }

    public function getById($id){
        return Activity::query()->with("resources")->find($id);
    }

    public function update(UpdateRequest $request,$id){
        return Db::transaction(function () use($request,$id){
            $activity = Activity::query()->findOrFail($id);
            $activity->fill($request->all());
            $activity->save();

            Resource::query()->where([['source_id',$id],['origin',Constant::ORIGIN_ACTIVITY]])->delete();

            $resources = $request->input("resources");
            foreach ($resources as $v){
                $resource = new Resource();
                $resource->setAttribute("source_id",$id);
                $resource->setAttribute("uri",$v);
                $resource->setAttribute("origin",Constant::ORIGIN_ACTIVITY);
                $resource->save();
            }
        });
    }

    public function show($id){
        $model = Activity::query()->findOrFail($id);
        $model->setAttribute("is_show",$model->getAttribute("is_show") % Constant::ACTIVITY_SHOW + 1);
        return $model->save();
    }

    public function finish($id){
        $model = Activity::query()->findOrFail($id);
        $model->setAttribute("status",Constant::ACTIVITY_STATUS_FINISH);
        return $model->save();
    }
}